/**
*@Author: QWP
*@Description: 群聊相关的共享数据
*@Date 2025-01-14 09:11
*/
import dayjs from 'dayjs';
import { defineStore } from 'pinia'

interface ChatState {
  recallMsgs: object, 
}


export const useChatStore = defineStore('chatStore', {
  state: (): ChatState => {
    return {
      recallMsgs: {}, // 测绘缓存消息
    }
  },
  actions: {
    setRecallMsgs(data: object) {
      this.recallMsgs = data;
      clearRecallMsg()
    },
  },
  persist: true
})


/**
*@Author: QWP
*@Description: 定时清理
*@Date 2025-01-14 10:02
*/
let clearTimer: any = null;
let clearDate: string = '';
const clearRecallMsg = () => {
  const store = useChatStore()
  const data = store.recallMsgs;
  const keys = Object.keys(data || {});
  const key = keys[0] || ''

  if(clearTimer == null) {
    if(clearDate == '' && key != '') {
      clearDate = data[key]['clearDate'];
      let millisecond = dayjs(clearDate).valueOf() - dayjs().valueOf();
      clearTimer = setTimeout(() => {
        const result = clearHandle(data)
        store.setRecallMsgs(result)

        clearTimeout(clearTimer)

        clearTimer = null;
        clearDate = '';

        clearRecallMsg()
      }, millisecond)
    }
  }
}

const clearHandle = (data: object): object => {
  for(let key in data) {
    const item = data[key]
    if(!item['clearDate']) {
      delete data[key]
    }
    else if(dayjs(item['clearDate']).isBefore(dayjs(clearDate))) {
      delete data[key]
    }
    else if(dayjs(item['clearDate']).format('YYYY-MM-DD HH:mm') == dayjs(clearDate).format('YYYY-MM-DD HH:mm')) {
      delete data[key]
    }
  }
  return data
}
